package com.xh.bussiness.jingyou.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.jingyou.constants.JingYouConstants;
import com.xh.bussiness.jingyou.model.JYUser;
import com.xh.bussiness.jingyou.model.JYUserCallLog;
import com.xh.bussiness.jingyou.service.IJYAuthService;
import com.xh.bussiness.jingyou.service.IJYUserCallLogService;
import com.xh.bussiness.jingyou.service.IJYUserService;
import com.xh.bussiness.jingyou.utils.DES3;
import com.xh.bussiness.jingyou.utils.Utility;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.HttpUtils;
import com.xh.core.util.StringUtils;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author JQM
 * @since 2019-11-11
 */
@Service
public class JYAuthServiceImpl implements IJYAuthService{
	
	@Autowired
	private IJYUserService jyUserService;
	@Autowired
	private IJYUserCallLogService jyUserCallLogService;
	

	@Override
	public String getToken() throws Exception {
//		String token = login(null,null);
		return getToken(null,null);
	}
	/**
	 * 获取token
	 * 
	 * @return
	 * @throws Exception 
	 */
	@Override
	public String getToken(Integer type, Integer count) throws Exception {
		JYUser user = getAvailableJYUser(type, count);
		System.out.println("-----user------" + user.getAccount() + "-----" + user.getPassword());
		// 插入调用记录
		JYUserCallLog log = new JYUserCallLog();
		log.setUserId(user.getId());
		log.setType(type);
		log.setDeleted(0);
		jyUserCallLogService.insert(log);
		String token = (String) CacheUtils.get("jyuser-"+user.getAccount());
		if (StringUtils.isEmpty(token) || token.length() < 200) {
			token = login(user);
			System.out.println("token*****" + token);
			CacheUtils.set("jyuser-"+user.getAccount(), token, 60 * 60 * 24 * 5);
		}
		return token;
	}
	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login(JYUser user) {
		try {
			
			String s = String.format("%s#@@#%s#@@#%s", JingYouConstants.ACCOUNT_API_ID, user.getAccount(), user.getPassword());
			String v = DES3.encrypt(s, JingYouConstants.ACCOUNT_API_KEY);

			String url = String.format("http://api.jyeoo.com/v1/user?id=%s&v=%s", JingYouConstants.ACCOUNT_API_ID, v);

			String result = Utility.sendPost(null, url, String.class);
			System.out.println("url****"+url);
			System.out.println("---------------------" + result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public JYUser getAvailableJYUser(Integer type, Integer count) throws Exception{
		if(type == null){
			JYUser user=jyUserService.selectFirst(new QueryWrapper<>());
			return user;
		}
		JYUser user = jyUserService.getAvailableUser(type);
		return user;
	}
}
